/**
 * @author denis.onishchenko@gmail.com
 */

package com.prapp.mediag;

import java.util.Collection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.feeder.SectionListViewAdapter;

public final class FeedsActivity extends Activity {

    private static final int G_ROOT = -10;
    private static final int G_FILTER = -11;

    private static final int M_SHOW_ALL = -12;
    private static final int M_MARK_ALL = -13;
    private static final int M_FILTER = -14;
    private static final int M_SETTINGS = -15;

    private static final int D_SETTINGS = -16;


    private int tabIndex;
    private PRApplication application;
    private Repository repository;
    private SectionListViewAdapter repositoryAdapter;
    private ImageButton updateButton;
    private SubMenu categoryFilterSubMenu;
    private Handler handler = new Handler();


    private boolean fetchRunning = false;
    private Runnable fetchJob = new Runnable() {
        public void run() {
            fetchRunning = true;

            handler.post(new Runnable() {
                public void run() {
                    updateButton.setImageDrawable(getResources().getDrawable(R.drawable.posts_update_cancel_selector));
                }
            });

            try {
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                int wifiState = wifiManager.getWifiState();
                boolean wifiEnabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
                int downloadImagesCode = application.getDownloadImages();
                boolean downloadImages = (downloadImagesCode == 2) || (downloadImagesCode == 1 && wifiEnabled);

                repository.fetch(downloadImages);
            }
            finally {
                fetchRunning = false;

                boolean unread = application.getShowUnreadPosts();
                repository.synchronize(unread);

                handler.post(new Runnable() {
                    public void run() {
                        repositoryAdapter.notifyDataSetChanged();
                        updateButton.setImageDrawable(getResources().getDrawable(R.drawable.posts_update_selector));
                    }
                });
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feeds);

        Bundle extras = getIntent().getExtras();

        fetchRunning = false;
        tabIndex = extras.getInt(PRApplication.TAB_INDEX);
        application = (PRApplication) getApplication();
        repository = application.getRepository(tabIndex);
        repositoryAdapter = new SectionListViewAdapter(FeedsActivity.this, R.layout.feeds_item_section, R.layout.feeds_item, repository) {

            protected View onSectionView(String section, View view) {
                TextView textView = (TextView) view.findViewById(R.id.tvSection);
                textView.setText(section);
                return view;
            }

            protected View onItemView(long id, View view) {
                Post post = repository.getPostById(id);

                int drawable = post.getRead() ? R.drawable.feeds_item_selector : R.drawable.feeds_item_unread_selector;
                view.setBackgroundResource(drawable);

                TextView categoryNameTextView = (TextView) view.findViewById(R.id.tvCategoryName);
                TextView postTitleTextView = (TextView) view.findViewById(R.id.tvPostTitle);
                ImageView favoriteImageView = (ImageView) view.findViewById(R.id.ivPostFavoriteIcon);
                TextView postContentTextView = (TextView) view.findViewById(R.id.tvPostContent);

                categoryNameTextView.setText(repository.getCategoryById(post.getCategoryId()).getName());
                postTitleTextView.setText(post.getTitle());
                favoriteImageView.setImageResource(post.getFavorite() ? R.drawable.posts_post_favorite : R.drawable.posts_post_not_favorite);
                postContentTextView.setText(post.getDescription());

                return view;
            }
        };
        updateButton = (ImageButton) findViewById(R.id.bUpdate);
        updateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (!fetchRunning)
                    new Thread(fetchJob).start();
                else
                    repository.cancelFetch();
            }
        });


        try {
            application.trackPageView("/posts");
        }
        catch (Throwable x) {
            Log.e(getClass().getName() + ".onCreate", "Can't track page view", x);
        }


        long categoryId = application.getCategoryId();
        Category category = repository.getCategoryById(categoryId);
        if (category == null) {
            categoryId = Category.ALL_CATEGORY_ID;
            category = repository.getCategoryById(categoryId);
        }
        repository.setCategory(category);

        Config.Tab tab = application.getTab(tabIndex);
        String title = tab.getName();
        if (title != null) {
            TextView titleTextView = (TextView) findViewById(R.id.tvTitle);
            titleTextView.setText(title);
        }

        ListView postListView = (ListView) findViewById(R.id.lvPosts);
        postListView.setAdapter(repositoryAdapter);
        postListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                id = repositoryAdapter.getId(position);
                onShowArticle(id);
            }
        });
        postListView.setOnScrollListener(repositoryAdapter);

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();

        if (application.getSyncItemsOnStart())
            new Thread(fetchJob).start();
    }

    protected void onResume() {
        super.onResume();

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem showAllUnreadItem = menu.add(G_ROOT, M_SHOW_ALL, Menu.NONE, R.string.ShowUnread);
        showAllUnreadItem.setIcon(R.drawable.posts_menu_show_all_unread);

        MenuItem markAllAsReadItem = menu.add(G_ROOT, M_MARK_ALL, Menu.NONE, R.string.MarkAllAsRead);
        markAllAsReadItem.setIcon(R.drawable.posts_menu_mark_all_as_read);


        categoryFilterSubMenu = menu.addSubMenu(G_ROOT, M_FILTER, Menu.NONE, R.string.FilterByCategory);
        categoryFilterSubMenu.setIcon(R.drawable.posts_menu_category_filter);

        Collection<Category> categories = repository.getCategories();

        for (Category category : categories) {
            int categoryId = category.getId().intValue();
            String categoryName = category.getName();
            categoryFilterSubMenu.add(G_FILTER, categoryId, Menu.NONE, categoryName);
        }

        categoryFilterSubMenu.setGroupCheckable(G_FILTER, true, true);


        MenuItem settingsItem = menu.add(G_ROOT, M_SETTINGS, Menu.NONE, R.string.Settings);
        settingsItem.setIcon(R.drawable.posts_menu_settings);


        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem showAllUnreadItem = menu.findItem(M_SHOW_ALL);
        int showAllUnreadTitleId = application.getShowUnreadPosts() ? R.string.ShowAll : R.string.ShowUnread;
        showAllUnreadItem.setTitle(showAllUnreadTitleId);


        long categoryId = application.getCategoryId();

        Category currentCategory = repository.getCategoryById(categoryId);

        if (currentCategory == null) {
            categoryId = Category.ALL_CATEGORY_ID;
            repository.getCategoryById(categoryId);
        }

        Collection<Category> categories = repository.getCategories();

        long postCount = repository.getPostCount();

        for (Category category : categories) {
            int id = category.getId().intValue();
            String title = category.getName() + " (" + (Category.isAll(id) ? String.valueOf(postCount) : repository.getCategoryPostCount(id) + "/" + postCount) + ")";

            MenuItem item = categoryFilterSubMenu.findItem(id);
            item.setTitle(title);

            if (categoryId == category.getId())
                item.setChecked(true);
        }


        return super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int groupId = item.getGroupId();
        int itemId = item.getItemId();

        switch (groupId) {
            case G_ROOT:
                switch (itemId) {
                    case M_SHOW_ALL:
                        onShowAllUnread();
                        return true;

                    case M_MARK_ALL:
                        onMarkAllAsRead();
                        return true;

                    case M_SETTINGS:
                        showDialog(D_SETTINGS);
                        return true;
                }

            case G_FILTER:
                if (itemId > -10) {
                    onFilerByCategory(itemId);
                    return true;
                }
        }

        return super.onOptionsItemSelected(item);
    }

    protected Dialog onCreateDialog(int id) {
        if (D_SETTINGS == id)
            return onCreateSettingsDialog();

        return super.onCreateDialog(id);
    }

    protected void onPrepareDialog(int id, Dialog dialog) {
        if (D_SETTINGS == id) {
            onPrepareSettingsDialog(dialog);
            return;
        }

        super.onPrepareDialog(id, dialog);
    }

    private Dialog onCreateSettingsDialog() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.settings, null);


        Spinner downloadImagesSpinner = (Spinner) view.findViewById(R.id.sDownloadImages);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.download_images, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        downloadImagesSpinner.setAdapter(adapter);

        downloadImagesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                application.setDownloadImages(position);
            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        CheckBox syncCheckBox = (CheckBox) view.findViewById(R.id.cbSync);
        syncCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                application.setSyncItemsOnStart(isChecked);
            }
        });


        Button deleteAllImagesButton = (Button) view.findViewById(R.id.bDeleteAllImages);
        deleteAllImagesButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                repository.deleteAllImages();
            }
        });


        Button deleteOldPostsButton = (Button) view.findViewById(R.id.bDeleteOldPosts);
        deleteOldPostsButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onDeleteOldPosts();
            }
        });


        Button deleteAllPostsButton = (Button) view.findViewById(R.id.bDeleteAllPosts);
        deleteAllPostsButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onDeleteAllPosts();
            }
        });


        return new AlertDialog.Builder(this)
                .setTitle(R.string.Settings)
                .setCancelable(false)
                .setView(view)
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
                        int action = event.getAction();

                        if (action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                            Dialog dialog = (Dialog) dialogInterface;
                            dialog.dismiss();
                            return true;
                        }

                        return false;
                    }
                })
                .create();
    }

    private void onPrepareSettingsDialog(Dialog dialog) {
        CheckBox syncCheckBox = (CheckBox) dialog.findViewById(R.id.cbSync);
        Spinner downloadImagesSpinner = (Spinner) dialog.findViewById(R.id.sDownloadImages);

        syncCheckBox.setChecked(application.getSyncItemsOnStart());
        downloadImagesSpinner.setSelection(application.getDownloadImages());
    }

    private void onShowAllUnread() {
        boolean unread = !application.getShowUnreadPosts();
        application.setShowUnreadPosts(unread);

        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }

    private void onMarkAllAsRead() {
        repository.markAllAsRead();

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }

    private void onFilerByCategory(long categoryId) {
        application.setCategoryId(categoryId);

        Category category = repository.getCategoryById(categoryId);

        repository.setCategory(category);

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }

    private void onShowArticle(long postId) {
        Intent intent = new Intent(this, ArticleActivity.class);

        intent.putExtra(PRApplication.TAB_INDEX, tabIndex);
        intent.putExtra(PRApplication.POST_ID, postId);

        startActivity(intent);
    }

    private void onDeleteOldPosts() {
        repository.deleteOldPosts();

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }

    private void onDeleteAllPosts() {
        repository.deleteAllPosts();

        boolean unread = application.getShowUnreadPosts();
        repository.synchronize(unread);
        repositoryAdapter.notifyDataSetChanged();
    }
}
